/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package per.wsj.andratingbar.adapter;

import ohos.agp.components.*;
import ohos.app.Context;
import per.wsj.andratingbar.ResourceTable;
import per.wsj.library.AndRatingBar;

import java.util.List;
import java.util.Optional;

/**
 * MyAdapter
 *
 * @since 2021-04-13
 */
public class MyAdapter extends BaseItemProvider {
    private static final int STAR_SIZE = 6;
    private Context context;
    private List<String> mData;

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param data 数据
     */
    public MyAdapter(Context context, List<String> data) {
        this.context = context;
        this.mData = data;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public Object getItem(int position) {
        if (mData != null && position >= 0 && position < mData.size()) {
            return mData.get(position);
        }
        return Optional.empty();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int index, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_rv_item, null, false);
        } else {
            cpt = component;
        }
        Text text = (Text) cpt.findComponentById(ResourceTable.Id_name);
        AndRatingBar andRatingBar = (AndRatingBar) cpt.findComponentById(ResourceTable.Id_andRatingBar);
        text.setText(mData.get(index));
        andRatingBar.setScore(index % STAR_SIZE);
        return cpt;
    }

}